package com.youlu.campus.admin.tencentcloud.service.impl;

import com.youlu.campus.admin.tencentcloud.entity.DnsRecordQueryVo;
import com.youlu.campus.admin.tencentcloud.entity.TencentDomainItem;
import com.youlu.campus.admin.tencentcloud.service.TencentDomainItemService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.support.PageableExecutionUtils;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * 腾讯域名项服务
 *
 * @Description: TencentDomainItemService
 * @Date 2025/11/3
 * @module TencentDomainItemService
 * @author: su
 */
@Slf4j
@Service
public class TencentDomainItemServiceImpl implements TencentDomainItemService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void deleteAll() {
        mongoTemplate.remove(new Query(), TencentDomainItem.class);
    }

    @Override
    public void insertAll(List<TencentDomainItem> list) {
        mongoTemplate.insertAll(list);
    }

    @Override
    public Page<TencentDomainItem> findByPage(DnsRecordQueryVo paramVo) {
        Query query = new Query();
        if (StringUtils.isNotBlank(paramVo.getKeyword())) {
            query.addCriteria(Criteria.where("domain").regex(paramVo.getKeyword(), "i"));
        }
        //统计总条数（分页需要先查总数）
        long total = mongoTemplate.count(query, TencentDomainItem.class);
        //创建分页对象
        Pageable pageRequest = PageRequest.of(paramVo.getPage() - 1, paramVo.getPageSize());
        List<TencentDomainItem> list;
        if (total == 0) {
            list = Arrays.asList();
        } else {
            // 应用分页（设置跳过的条数和查询的条数）
            query.skip(pageRequest.getOffset()).limit(pageRequest.getPageSize());
            list = mongoTemplate.find(query, TencentDomainItem.class);
        }
        return PageableExecutionUtils.getPage(list, pageRequest, () -> total);
    }
}
